import { createStore } from 'vuex'

// 将购物车数据保存到 localStorage
const setLocalCartList = (state) => {
  const { cartList } = state
  const cartListString = JSON.stringify(cartList)
  localStorage.cartList = cartListString
}

// 从 localStorage 获取购物车数据
const getLocaCartList = () => {
  try {
    return JSON.parse(localStorage.cartList || '{}')
  } catch (error) {
    return {}
  }
}

export default createStore({
  state: {
    // 购物车数据结构：
    // cartList: {
    //   shopId: {
    //     shopName: '沃尔玛',
    //     productList: {
    //       productId: {
    //         _id: '1',
    //         name: '番茄 250g',
    //         imgUrl: 'xxx.png',
    //         sales: 10,
    //         price: 33.6,
    //         oldPrice: 39.6,
    //         count: 2
    //       }
    //     }
    //   }
    // }
    cartList: getLocaCartList()
  },
  mutations: {
    // 修改购物车中的商品数量
    changeCartItemInfo(state, payload) {
      const { shopId, productId, productInfo, num } = payload
      // 获取店铺信息，如果不存在则初始化
      let shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      // 获取商品信息，如果不存在则初始化
      let product = shopInfo.productList[productId]
      if(!product) {
        product = productInfo
        product.count = 0
      }
      // 修改商品数量
      product.count = product.count + num
      if(product.count < 0) { product.count = 0 }
      
      // 更新 store 和 localStorage
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    // 修改店铺名称
    changeShopName(state, payload) {
      const { shopId, shopName } = payload
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    // 清空店铺购物车
    cleanCartProducts(state, payload) {
      const { shopId } = payload
      state.cartList[shopId].productList = {}
      setLocalCartList(state)
    }
  },
  getters: {
    // 获取店铺商品总数
    getShopCartCount: (state) => (shopId) => {
      let count = 0
      const productList = state.cartList[shopId]?.productList
      if(productList) {
        for(let i in productList) {
          const product = productList[i]
          count += product.count
        }
      }
      return count
    },
    // 获取店铺商品总价
    getShopCartPrice: (state) => (shopId) => {
      let total = 0
      const productList = state.cartList[shopId]?.productList
      if(productList) {
        for(let i in productList) {
          const product = productList[i]
          total += (product.price * product.count)
        }
      }
      return total.toFixed(1)
    }
  }
})
